<template>
  <el-dialog @close="close" :title="!formData.id?'添加用户':'修改用户'" :visible.sync="dialogFormVisible">
    <el-form
      :model="formData"
      ref="formData"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item prop="username" label="用户名">
        <el-input v-model="formData.username" size="small"></el-input>
      </el-form-item>
      <el-form-item prop="nickName" label="用户名称">
        <el-input v-model="formData.nickName" size="small"></el-input>
      </el-form-item>
      <el-form-item
        v-if="!formData.id"
        prop="password"
        label="用户密码"
      >
        <el-input v-model="formData.password" size="small"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="onSave">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import projectApi from "@/api/project";
import { Message } from "element-ui";

export default {
  name: "Vue2Model",
  data() {
    var validUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("名称不能为空"));
      }
      if (value.length < 5) {
        return callback(new Error("品牌需大于4个字"));
      }
      return callback();
    };
    var valiPassWord = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("密码不能为空"));
      }
      if (value.length < 6) {
        return callback(new Error("品牌需大于5个字"));
      }
      return callback();
    };
    return {
      dialogFormVisible: false,
      formData: {
        nickName: "",
        password: "",
        username: "",
      },
      rules: {
        username: [{ validator: validUserName, trigger: "blur" }],
        password: [{ validator: valiPassWord, trigger: "blur" }],
      },
    };
  },
  mounted() {},
  methods: {
    // 点击保存
    async onSave() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.reqSave();
        } else {
          return false;
        }
      });
    },
    // 保存发送数据
    async reqSave() {
      try {
        console.log(this.formData);
        await projectApi.addUser(this.formData);
        Message.success("保存成功");
        this.dialogFormVisible = false;
        this.$bus.$emit("reqUserList");
      } catch (error) {
        Message.error(error)
      }
    },
    // 关闭
    close() {
      this.formData = {};
    },
  },
};
</script>

<style lang="scss" scoped></style>
